package cn.maka.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/lastTimeServlet")
public class LastTimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        //boolean isFirst = false;
        String lastTime = "您好，欢迎您首次访问";
        String remoteAddr="你上次没有登陆";

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String formatDate = simpleDateFormat.format(date);
        formatDate = URLEncoder.encode(formatDate, "utf-8");

        Cookie lastTimeCookie = new Cookie("lastTime", formatDate);

        String newRemoteAddr = request.getRemoteAddr();

        Cookie ipCookie = new Cookie("RemoteAddr", newRemoteAddr);

        lastTimeCookie.setMaxAge(604800);
        ipCookie.setMaxAge(604800);
        response.addCookie(lastTimeCookie);
        response.addCookie(ipCookie);

        //System.out.println(cookies);

        response.setContentType("text/html;charset=utf-8");

        if (cookies != null && cookies.length > 0) {

            for (Cookie cookie : cookies) {
                if ("lastTime".equals(cookie.getName())) {
                    lastTime = cookie.getValue();

                    lastTime = URLDecoder.decode(lastTime, "utf-8");

                    lastTime = "欢迎回来，您上次访问时间为" + lastTime;

                    //response.getWriter().write("欢迎回来，您上次访问时间为" + lastTime);

                    //isFirst = false;

                    //break;

                }

                if ("RemoteAddr".equals(cookie.getName())){
                    remoteAddr="您上次登录IP为："+cookie.getValue();
                    //isFirst = false;
                }

            }
        }

        /*if (isFirst) {
            lastTime="您好，欢迎您首次访问";
            remoteAddr="你上次没有登陆";
            //response.getWriter().write("您好，欢迎您首次访问");
        }*/

        response.getWriter().write(lastTime+"<br>"+remoteAddr);



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
